/*
	Class: BASIK.External.ExternalInterfaceManager
	
		Oversees communication via the Flash External Interface. 
		
*/
package com.frontalcode 
{
	import flash.external.*; 
	
	/**
	 * The ExternalInterfaceManager class handles the Frontal-JavaScript
	 * interface.
	 */
    public class ExternalInterfaceManager extends OptionableObject
    {
		private static var _instance : ExternalInterfaceManager;
	
		/*
			Constructor: ExternalInterfaceManager
			
				This class is a singleton.
		*/
		/**
		 * @private
		 */
		function ExternalInterfaceManager ( options : Object = null )
		{
			super ( options );
			
			setObjectOptionDefault ( "enableExternalEval", false );
			setOptionsFromLoaderParameters ( );
			
			if ( getObjectOption ( "enableExternalEval" ) ) addFrontalEvalCallback ( );
		}
		
		/*
			Function: getInstance
			
				Returns the single instance of this class.
		*/
		/**
		 * The single instance of the ExternalInterfaceManager class.
		 *
		 * @return The ExternalInterfaceManager instance.
		 */
		public static function getInstance ( ) : ExternalInterfaceManager 
		{
			if ( _instance == null ) _instance = new ExternalInterfaceManager ( );
			return _instance;
		}
		
		// Convenience method.
		//
		/**
		 * The single instance of the ExternalInterfaceManager class.
		 *
		 * @return The ExternalInterfaceManager instance.
		 */
		public static function gI ( ) : ExternalInterfaceManager { return getInstance ( ); }
		
		/*
			Function: addFrontalEvalCallback
				
				Enables this ExternalInterfaceManager to receive calls from external code.
						
				For callbacks to work, the Flash movie must be set up with:
				
				OBJECT id="movie" and no name attribute
				EMBED name="movie" and no id attribute
				
				Then, callback in js like this:
				
				internal function callExternalInterface(cmd) {
					var result=thisMovie("movie").frontalEval(cmd);
				}
	
				internal function thisMovie(movieName) {
					if (navigator.appName.indexOf("Microsoft") != -1) {
						return window[movieName]
					}
					else {
						return document[movieName]
					}
				}			
			
			Returns: 
				
				Boolean - If the call succeeded, returns true. If it failed because the instance was not
				available, a security restriction was encountered, there was no such function object, a 
				recursion occurred, or something similar, returns false.			
		
		*/
		public function addFrontalEvalCallback ( ) : void
		{
			ExternalInterface.addCallback ( "frontalEval", frontalEval );
		}	
		
		private function frontalEval ( cmd : String ) : *
		{		
			return ActionScriptInterpreter.evaluate ( cmd, DocumentManager.getInstance ( ), null, { } );
		}
	}
}